package com.hp.bon.sgw.util;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Properties;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class LogBackConfigTool {



	public static void updateAllLogBackProperty(String filePath,
			String propName, String propValue) throws Exception {
		File path = new File(filePath);
		for (File file : path.listFiles()) {
			String fileName = file.getAbsolutePath();
			if (file.isFile() && fileName.contains("logback")
					&& fileName.endsWith(".xml")) {
				changeLogbackProperty(fileName, propName, propValue);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static void changeLogbackProperty(String fileName, String propName,
			String propValue) throws Exception {
		File file = new File(fileName);
		if (file != null && file.isFile()) {
			SAXReader sb = new SAXReader();
			Document doc = sb.read(file);
			Element root = doc.getRootElement();
			List<Element> els = root.elements("property");
			String attrName = propName;
			boolean updated = false;
			for (Element propEL : els) {
				if (propEL.attributeValue("name", "").equals(attrName)) {
					propEL.addAttribute("value", propValue);
					updated=true;
					break;
				}
			}
			if (updated) {
				saveXML(fileName, doc);
			}
		}
	}

	private static void saveXML(String path, Document doc) throws Exception {
		FileOutputStream fos = new FileOutputStream(path);
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(fos, format);
		writer.write(doc);
		writer.flush();

	}

	// 修改logback.xml关于日志大小的配置，若有多个appender-maxFileSize节点，则都会被改掉。
	@SuppressWarnings("unchecked")
	public static String changeSizeLog(String logbackFileName, String size)
			throws DocumentException {
		StringBuffer retVal = new StringBuffer();
		File file = new File(logbackFileName);
		if (file != null && file.isFile()) {
			SAXReader sb = new SAXReader();
			Document doc = sb.read(file);
			Element root = doc.getRootElement();
			List<Element> lAppender = root.elements("appender");
			if (lAppender != null && lAppender.size() > 0) {
				for (int i = 0; i < lAppender.size(); i++) {
					Element appenderE = lAppender.get(i);
					String appenderName = appenderE.attributeValue("name");
					Element triggerE = appenderE.element("triggeringPolicy");
					if (triggerE != null) {
						Element maxFileSizeE = triggerE.element("maxFileSize");
						if (maxFileSizeE != null) {
							maxFileSizeE.setText(size);
							retVal.append("Change log size of appender "
									+ appenderName + " to " + size
									+ " successfully.");
						}
					}
				}
			} else {
				retVal.append("Change log size failed,because not find '<appender' in file "
						+ logbackFileName + "!");
			}

		} else {
			retVal.append("Change log size failed,because file "
					+ logbackFileName + " not find!");
		}
		return retVal.toString();
	}
	// 修改RmiAgent.properties文件的配置值，tag为属性名称（SGW_logArchivePath），mirrorPath为属性值（绝对路径）
	public static void save2PropertiesFile(String tag, String value,
			String propFile) throws Exception {
		Properties _prop = Comutils.getPropertiesFromFile(propFile);
		_prop.put(tag, value);
		FileOutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(propFile);
			_prop.store(outputStream, "updated");
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
}
